package cn.tedu.knows.resource.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
//跨域注解
@CrossOrigin
@Slf4j
//配置中配置了Servlet上下文路径/image
//所以这个控制器路径为/image/file
@RequestMapping("/file")
public class ImageController {
    @Value("${knows.resource.path}")
    private File resourcePath;

    @Value("${knows.resource.host}")
    private String resourceHost;

    @PostMapping
    //MultipartFile 是SpringMVC框架提供的类型,专门用于接收上传的文件
    //imageFile 表单中文件域name一致
    public String uploadFile(MultipartFile imageFile) throws IOException {
        //根据日期获得path路径
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDate.now());
        //path : 2021/11/03
        //确定上传的路径
        File folder = new File(resourcePath,path);
        //创建文件夹
        folder.mkdirs();

        //随机文件名
        String filename = imageFile.getOriginalFilename();//原始文件名

        String ext = filename.substring(filename.lastIndexOf("."));

        String name = UUID.randomUUID().toString()+ext;

        //确定要上传的路径
        File file = new File(folder,name);
        log.debug("上传的路径为:{}",file.getAbsoluteFile());

        //执行上传
        imageFile.transferTo(file);

        //回显的关键,是上传控制返回通过静态资源服务器访问资源的路径
        String url= resourceHost+"/"+path+"/"+name;
        log.debug("生成的Url:{}",url);

        //返回url,以实现页面回显上传的图片
        return url;
    }
}
